package datos;

import java.util.Arrays;

public class CSVBuilder<Line, Result> implements IBuilder<String, Result> {

    private IBuilder<String, Line> lineBuilder;
    private IBuilder<Line, Result> resultBuilder;
    private String separator;

    public CSVBuilder(IBuilder<String, Line> lineBuilder, 
                IBuilder<Line, Result> resultBuilder) {
        this(lineBuilder, resultBuilder, ",");
    }

    public CSVBuilder(IBuilder<String, Line> lineBuilder,
            IBuilder<Line, Result> resultBuilder,
            String separator) {

       this.lineBuilder = lineBuilder;
       this.resultBuilder = resultBuilder;
       this.separator = separator;

       this.reset();
    }

    
    @Override
    public void add(String s) {
        /* Esto quizas deber�a ser m�s gen�rico */
        String[] tokens = s.split(this.separator);
        for (String token : tokens) {
            this.lineBuilder.add(token.trim());                    
        }
        this.resultBuilder.add(this.lineBuilder.finish());
        this.lineBuilder.reset();
    }

    @Override
    public Result finish() {
        Result result = this.resultBuilder.finish();

        this.reset();

        return result;
    }

    @Override
    public void reset() {
        if (this.lineBuilder != null) {
            this.lineBuilder.reset();
        } else {
            /* TODO: this has to go */
            System.out.println("lineBuilder is null");
        }
        if (this.resultBuilder != null) {
            this.resultBuilder.reset();
        } else {
            System.out.println("resultBuilder is null");
        }
    }
}
